﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

using System.Data.SqlClient;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace HoaDon
{
	public partial class Login : System.Web.UI.Page
	{
		protected void Page_Load(object sender, EventArgs e)
		{
		}

		protected void cLogin_Authenticate(object sender, AuthenticateEventArgs e)
		{
			try
			{
				if (CheckLogin(cLogin.UserName, cLogin.Password) == true)
				{
					FormsAuthentication.RedirectFromLoginPage(cLogin.UserName.ToUpper(), cLogin.RememberMeSet);
					e.Authenticated = true;
				}
				else
					e.Authenticated = false;
			}
			catch
			{
				Response.Redirect("~/Error.aspx", false);
			}
		}

		private bool CheckLogin(string userid, string pass)
		{
			SqlConnection proxyConn = new SqlConnection(WebConfigurationManager.ConnectionStrings["proxyconn"].ConnectionString);
			proxyConn.Open();
			try
			{
				SqlCommand sqlComm = new SqlCommand("SELECT FK_DatabaseID, ListKhoID FROM userinfo WHERE UPPER(UserID) = @UserID AND Password = @Password AND Status = '1'", proxyConn);
				sqlComm.CommandType = CommandType.Text;
				sqlComm.Parameters.Add("@UserID", SqlDbType.VarChar).Value = userid.ToUpper();
				sqlComm.Parameters.Add("@Password", SqlDbType.VarChar).Value = Enc.Encrypt(pass, userid.ToUpper());
				SqlDataAdapter sqlDA = new SqlDataAdapter();
				sqlDA.SelectCommand = sqlComm;
				DataTable dtUserInfo = new DataTable();
				sqlDA.Fill(dtUserInfo);

				if (dtUserInfo.Rows.Count > 0)
				{
					SqlCommand sqlComm2 = new SqlCommand("EXEC [get_DatabaseConnection] '" + userid.ToUpper() + "'", proxyConn);
					sqlComm2.CommandType = CommandType.Text;
					SqlDataAdapter sqlDA2 = new SqlDataAdapter();
					sqlDA2.SelectCommand = sqlComm2;
					DataTable dtDC = new DataTable();
					sqlDA2.Fill(dtDC);

					Session["strConn"] = dtDC.Rows[0]["ConnectionString"].ToString();
					Session["FK_DatabaseID"] = dtUserInfo.Rows[0]["FK_DatabaseID"].ToString();
					Session["ListKhoID"] = dtUserInfo.Rows[0]["ListKhoID"].ToString();

					proxyConn.Close();
					proxyConn.Dispose();
					return true;
				}
				else
				{
					proxyConn.Close();
					proxyConn.Dispose();
					return false;
				}
			}
			catch
			{
				proxyConn.Close();
				proxyConn.Dispose();
				return false;
			}
		}
	}
}
